package com.hw.controller;

import com.hw.config.shiro.jwt.JwtToken;
import com.hw.entity.dto.LoginDTO;
import com.hw.entity.po.sys.SysUser;
import com.hw.model.ResponseResult;
import com.hw.service.sys.SysUserService;
import com.hw.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登陆
 *
 * @author whw
 * @date 2021/6/15
 */
@Api(tags = "登陆")
@RestController
public class LoginController {
    @Autowired
    SysUserService sysUserService;

    @ApiOperation(value = "登陆")
    @PostMapping("/login")
    public ResponseResult<?> login(@RequestBody LoginDTO dto) {
        SysUser sysUser = sysUserService.getOne(dto.getUsername());
        if (ObjectUtils.isEmpty(sysUser) || !dto.getPassword().equals(sysUser.getPassword())) {
            throw new AuthenticationException("用户名或密码错误");
        }

        Subject subject = SecurityUtils.getSubject();
        String token = JwtUtils.sign(dto.getUsername());
        JwtToken jwtToken = new JwtToken(token);
        subject.login(jwtToken);
        return ResponseResult.success(token);
    }

    @ApiOperation(value = "退出登陆")
    @GetMapping("/logout")
    public ResponseResult<?> logout() {
        SecurityUtils.getSubject().logout();
        return ResponseResult.success();
    }
}
